# !/bin/sh
set -e
HASH_FILE_PATH="${HOME}/hash"
HASH_VALUE=""
ENV="$1"
MODULE="$2"
WORK_DIR=$(cd $(dirname $0) && pwd)

if [[ ! -n  "${ENV}" ]] || [[ ! -n "${MODULE}" ]] ;then
  echo "Please input environment and module name !"
  echo "Format: sh build.sh <dev> <module1>"
  exit 0
fi
# Entering workspace
MOD_PATH=${WORK_DIR}/${MODULE}
MOD_HASH=${HASH_FILE_PATH}/${MODULE}/hashfile.${ENV}

if [ ! -d "${HASH_FILE_PATH}/${MODULE}" ] ;then
  mkdir -p ${HASH_FILE_PATH}/${MODULE}
fi
if [ ! -x "$MOD_HASH" ];then
     touch ${MOD_HASH}
     INFO=`ls ${MOD_HASH}`
     echo "Module hash file:${INFO}"
fi
cd ${WORK_DIR}
HASH_VALUE=`git log --pretty=format:"%H" -1 ${MODULE}`
cd ${MOD_PATH}

NPM_VER=`npm --version`
PRVE_HASH=`head -n +1 ${MOD_HASH}`
echo  "\033[32mStart building...\033[0m"
echo  "Environment: \033[32m${ENV}\033[0m"
echo  "Last hash value of module: \033[32m${PRVE_HASH}\033[0m"
echo  "Aquire hash value of module: \033[32m${HASH_VALUE}\033[0m"
echo  "Npm version: \033[32m${NPM_VER}\033[0m"

if [ "$HASH_VALUE" != "$PRVE_HASH" ]; then
    npm run build:${ENV} --env=${ENV}
    echo ${HASH_VALUE} > ${MOD_HASH}
    echo "Build Complete."
else
    echo "\033[33mWarning: Therse's no commits to build.\033[0m" 
fi
